import React, { Component } from 'react'

export default class ItemTodo extends Component {
  refInput = React.createRef()

  state = {
    flag: false,
    showEdit: false,
  }

  //显示输入框
  editShow = () => {
    this.setState(
      {
        showEdit: true,
      },
      () => {
        this.refInput.current.value = this.props.item.name
        this.refInput.current.focus()
      }
    )
  }

  //隐藏输入框
  editHidden = () => {
    this.setState({
      showEdit: false,
    })
  }

  //修改done
  handleChange = (e) => {
    e.stopPropagation()
    const { target } = e // 表单元素必须含有name且与state保持一致
    this.props.editTodo(this.props.item.id, 'done', target.checked)
  }

  //修改name
  editItem = (e) => {
    const { keyCode, target } = e
    if (keyCode !== 13) return
    if (!target.value.trim().length) return alert('内容不能为空')
    this.props.editTodo(this.props.item.id, 'name', target.value)
    this.editHidden()
  }

  //删除
  handleDelete = () => {
    this.props.handleDel(this.props.item.id)
  }

  render() {
    const { item } = this.props
    return (
      <li
        className={[
          item.done ? 'completed' : '',
          this.state.showEdit ? 'editing' : '',
        ].join(' ')}
      >
        <input
          ref={this.refInput}
          style={{ display: this.state.showEdit ? 'block' : 'none' }}
          className="edit"
          onKeyUp={this.editItem}
          onBlur={this.editHidden}
        />
        <div
          className="view"
          style={{ display: this.state.showEdit ? 'none' : '' }}
        >
          <input
            className="toggle"
            type="checkbox"
            checked={item.done}
            onChange={this.handleChange}
            name="done"
          />
          <label onClick={this.editShow}>{item.name}</label>
          <button className="destroy" onClick={this.handleDelete}></button>
        </div>
      </li>
    )
  }
}
